package org.sixtynine.stock.controller;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.sixtynine.stock.Constants.CommonData;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.CategoryModule;
import org.sixtynine.stock.entity.Module;
import org.sixtynine.stock.entity.UserCategory;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.UserCategoryService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.util.SessionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilanka
 * 
 */
@Controller
public class UserCategoryController extends BackEndAuthController {

	@Autowired
	private GenericService genericService;

	@Autowired
	private DataManagerService dataManagerService;

	@Autowired
	UserCategoryService userCategoryService;

	/*
	 * This method use to set user category adding view
	 */
	@RequestMapping(value = "/admin/usercategory/add")
	public ModelAndView addUserCategoryPage(HttpServletRequest request) {
		ModelAndView modelAndView = null;
		boolean userLogged;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			userLogged = true;
			modelAndView = new ModelAndView("/admin/usercategory/add");
			// assign user category object to view
			modelAndView.addObject("userCategory", new UserCategory());
			modelAndView.addObject("userLogged", userLogged);
		} else {
			// TODO show an error message
			modelAndView = new ModelAndView("/login/login");
		}
		return modelAndView;
	}

	/*
	 * This method use to save user category
	 */

	@RequestMapping(value = "/admin/usercategory/add/process")
	public ModelAndView addUserCategory(
			@ModelAttribute @Valid UserCategory userCategory,
			BindingResult result) {

		if (!result.hasErrors()) {
			genericService.saveOrUpdate(userCategory);
			// in this method use to create list view..
			ModelAndView modelAndView = new ModelAndView(
					"/admin/usercategory/list");

			List<BaseEntity> userCategories = genericService
					.findAll(UserCategory.class);
			String message = "User Category was successfully added.";

			// assign data to list view
			modelAndView.addObject("userCategories", userCategories);
			modelAndView.addObject("message", message);

			dataManagerService.loadData(CommonData.USER_CATEGORY.toString(),
					UserCategory.class);

			return modelAndView;
		} else {
			// create user category adding view
			ModelAndView modelAndView = new ModelAndView(
					"/admin/usercategory/add");
			return modelAndView;
		}
	}

	/*
	 * This method use to view list of user categories
	 */
	@RequestMapping(value = "/admin/usercategory/list")
	public ModelAndView listUserCategories(HttpServletRequest request) {
		ModelAndView modelAndView = null;
		boolean userLogged;
		SessionBean sessionBean = SessionBean.getInstance(request);
		if (sessionBean.getUser() != null) {
			userLogged = true;
			modelAndView = new ModelAndView("/admin/usercategory/list");
			List<BaseEntity> userCategories = genericService
					.findAll(UserCategory.class);
			modelAndView.addObject("userCategories", userCategories);
			modelAndView.addObject("userLogged", userLogged);

		} else {
			// TODO show an error message
			modelAndView = new ModelAndView("/login/login");
		}

		return modelAndView;
	}

	/*
	 * This method use to set user category data into edit view
	 */
	@RequestMapping(value = "/admin/usercategory/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editUserCategory(HttpServletRequest request,
			@PathVariable Integer id) {
		ModelAndView modelAndView = new ModelAndView("/admin/usercategory/edit");

		UserCategory userCategory = (UserCategory) genericService.findById(id,
				UserCategory.class);
		Set<CategoryModule> categoryModules = userCategory.getCategoryModule();
		for (CategoryModule categoryModule : categoryModules) {
			userCategory.getModules().add(categoryModule.getModule());
		}

		// load the module list
		List<BaseEntity> modules = genericService.findAll(Module.class);
		modelAndView.addObject("modules", modules);

		modelAndView.addObject("userCategory", userCategory);

		return modelAndView;
	}

	/*
	 * This method use to update user category
	 */
	@RequestMapping(value = "/admin/usercategory/edit/{id}", method = RequestMethod.POST)
	public ModelAndView updateUserCategory(
			@ModelAttribute @Valid UserCategory userCategory,
			BindingResult result, @PathVariable Integer id) {

		if (!result.hasErrors()) {

			List<Module> modules = userCategory.getModules();
			for (Module module : modules) {
				module.setId(Integer.parseInt(module.getName()));

				CategoryModule categoryModule = new CategoryModule();
				categoryModule.setModule(module);
				categoryModule.setUserCategory(userCategory);

				userCategory.getCategoryModule().add(categoryModule);
			}

			// delete the existing modules
			userCategoryService.deleteModules(userCategory.getId());
			genericService.saveOrUpdate(userCategory);

			ModelAndView modelAndView = new ModelAndView(
					"/admin/usercategory/list");

			// get all user categories
			List<BaseEntity> userCategories = genericService
					.findAll(UserCategory.class);
			modelAndView.addObject("userCategories", userCategories);

			String message = "Team was successfully edited.";
			modelAndView.addObject("message", message);

			return modelAndView;
		} else {
			ModelAndView modelAndView = new ModelAndView(
					"/admin/usercategory/edit");
			return modelAndView;
		}
	}

	/*
	 * This method use to delete user category
	 */
	@RequestMapping(value = "/admin/usercategory/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteUserCategory(@PathVariable Integer id) {
		genericService.delete(id, UserCategory.class);

		ModelAndView modelAndView = new ModelAndView("/admin/usercategory/list");

		List<BaseEntity> userCategories = genericService
				.findAll(UserCategory.class);
		modelAndView.addObject("userCategories", userCategories);
		String message = "Team was successfully deleted.";
		modelAndView.addObject("message", message);
		return modelAndView;
	}

}
